//
//  AllMovieVc.swift
//  movieInfo
//
//  Created by zhangkai on 2023/5/17.
//

import UIKit
import MJRefresh
class AllMovieVc: BaseVC,UICollectionViewDelegate,UICollectionViewDataSource {
    
    var one:[Movie] = []
    private var collectionView: UICollectionView!
    var type:MovieInfoEndPoint = .topRated
    var page = 1
    
    func getData(){
        
        
        let url = MMNetWork.shared.getMoviesURL(endpoint: type, page: self.page)
        MMNetWork.shared.fetchData(urlString: url, castType: [Movie].self, keyPath: "results") { result in
            switch result {
            case .success(let movies):
//                completed(.success(movies))
                
                if self.page == 1{
                    self.one = movies
                }else{
                    self.one.append(contentsOf: movies)
                }
                
                
                
                DispatchQueue.main.async {
                    self.collectionView.reloadData()
                    
                    self.collectionView.mj_header?.endRefreshing()
                    self.collectionView.mj_footer?.endRefreshing()
                }
              
                break
            case .failure(let error):
                DispatchQueue.main.async {
                   
                    self.collectionView.mj_header?.endRefreshing()
                    self.collectionView.mj_footer?.endRefreshing()
                }
                break
            }
        }
        
        
        
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .white
        
        
        let mjheader = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(requestData))
        mjheader.lastUpdatedTimeLabel?.isHidden = true

        let foot_mj = MJRefreshBackNormalFooter(refreshingTarget: self, refreshingAction: #selector(onFooterRefresh))
        
        
        
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.sectionInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
        flowLayout.itemSize = CGSize(width: (UIScreen.main.bounds.width-45) / 2 - 5, height: 220)
        flowLayout.scrollDirection = .vertical
        
        collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: flowLayout)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(AllMovieVcCell.self, forCellWithReuseIdentifier: "AllMovieVcCell")
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.top.equalTo(topLayoutGuide.snp.bottom)
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.bottom.equalToSuperview()
//            make.edges.equalToSuperview()
            
        }
        collectionView.mj_header = mjheader
        collectionView.mj_footer = foot_mj
        
        getData()

        // Do any additional setup after loading the view.
    }
    
    @objc func requestData(){
        
        self.page = 1
        getData()
        
    }
    
    @objc func onFooterRefresh(){
        self.page = self.page + 1
        
        getData()
        
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.one.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "AllMovieVcCell", for: indexPath) as? AllMovieVcCell ?? AllMovieVcCell()
        
        let mov = self.one[indexPath.row]
       
        
        
        if let path = mov.posterPath {
            cell.img.downloadImage(fromPath: path)
        }
        cell.nameLabel.text = mov.title ?? ""
        cell.stattLabel.text = "\(mov.voteAverage ?? 0.0)"
        
        
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        let vc = ViewControllerInfoVC()
        vc.model = self.one[indexPath.row]
        vc.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(vc, animated: true)
    }

}


class AllMovieVcCell:UICollectionViewCell{
    
    var img = MIImageView(frame: CGRect(x: 0, y: 0, width: (UIScreen.main.bounds.width-45) / 2 - 5, height: 180))
    var nameLabel = UILabel()
    var stattImg = UIImageView()
    var stattLabel = UILabel()
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.addSubview(img)
        img.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.top.equalToSuperview()
//            make.width.equalTo(120)
            make.right.equalToSuperview()
            make.height.equalTo(180)
        }
        img.layer.masksToBounds = true
        img.contentMode = .scaleAspectFill
        
        nameLabel.text = "N/A"
        nameLabel.textColor = .black
        nameLabel.font = UIFont.boldSystemFont(ofSize: 16)
        contentView.addSubview(nameLabel)
        nameLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(5)
            make.right.equalToSuperview().offset(-5)
            make.top.equalTo(img.snp.bottom).offset(8)
        }
        
        stattImg.image = UIImage(named: "xingxing")
        contentView.addSubview(stattImg)
        stattImg.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(5)
            make.top.equalTo(nameLabel.snp.bottom).offset(5)
            make.width.equalTo(12)
            make.height.equalTo(12)
        }
        
        stattLabel.text = "N/A"
        stattLabel.textColor = .darkText
        stattLabel.font = UIFont.boldSystemFont(ofSize: 10)
        contentView.addSubview(stattLabel)
        stattLabel.snp.makeConstraints { make in
            make.centerY.equalTo(stattImg)
            make.left.equalTo(stattImg.snp.right)
         
        }
        
//
        
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
}
